package com.example.algorithm.linear.stack;

import java.util.Iterator;

/**
 * @program: algorithm
 * @description: 栈
 * @packagename: com.example.algorithm.linear.stack
 * @author: Jay
 * @date: 2022/04/24 16:16:04
 **/
public class Stack<T> implements Iterable<T>{

    //记录首结点
    private Node head;
    //栈中元素的个数
    private int N;



    private class Node{
        public T item;
        public Node next;

        public Node(T item, Node next){
            this.item = item;
            this.next = next;
        }

    }

    public Stack(){
        this.head = new Node(null, null);
        this.N = 0;
    }

    //判断栈是否为空
    public boolean isEmpty(){
        return N == 0;
    }

    //获取元素的个数
    public int size(){
        return N;
    }

    //把t元素压入栈中
    public void push(T t){
        //找到首结点指向的第一个结点
        Node oldFirst = head.next;
        //创建新节点
        Node newNode = new Node(t, null);
        //让首结点指向新节点
        head.next = newNode;
        //让新节点指向原来第一个结点
        newNode.next = oldFirst;
        //N++
        N++;
    }

    //弹栈
    public T pop(){
        //找到首结点指向的第一个结点
        Node oldFirst = head.next;
        //让首结点指向原来第一个结点的下一个结点
        if (oldFirst == null){
            return null;
        }
        head.next = oldFirst.next;
        N--;
        return oldFirst.item;

    }

    @Override
    public Iterator<T> iterator() {
        return new SIterator();
    }

    private class SIterator implements Iterator{

        private Node n;

        public SIterator(){
            this.n = head;
        }

        @Override
        public boolean hasNext() {
            return n.next != null;
        }

        @Override
        public Object next() {
            n = n.next;
            return n.item;
        }
    }

}
